from contextlib import asynccontextmanager

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

from app.api import doctors, plans, studies, token, users
from app.db import generate_schema, init_db
from app.logger import log

origins = [
    "http://localhost",
    "http://localhost:8080",
    "http://77.240.38.191",
]


@asynccontextmanager
async def lifespan(app: FastAPI):
    log.info("Starting up...")
    await generate_schema()
    init_db(app)
    yield
    log.info("Shutting down...")


def create_application() -> FastAPI:
    application = FastAPI(title="FastAPI Tortoise ORM", lifespan=lifespan)
    application.include_router(token.router, prefix="/login", tags=["auth token"])
    application.include_router(users.router, prefix="/admins", tags=["admins"])
    application.include_router(doctors.router, prefix="/doctors", tags=["doctors"])
    application.include_router(studies.router, prefix="/studies", tags=["studies"])
    application.include_router(plans.router, prefix="/plans", tags=["plans"])

    application.add_middleware(
        CORSMiddleware,
        allow_origins=origins,
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )

    return application


app = create_application()
